#include "server.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define P(func) do{perror("func");return -1;}while(0)

int server_init()
{
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1)
        P(socket);
    struct sockaddr_in ser,cli;
    ser.sin_family=AF_INET;
    ser.sin_port=htons(8989);
    ser.sin_addr.s_addr = inet_addr("192.168.211.121");
    //ser.sin_addr.s_addr=inet_addr("0.0.0.0");
    int cli_len=sizeof(cli);
    if(bind(sockfd,(struct sockaddr *)&ser,sizeof(ser))==-1)
        P(bind);
    printf("bind success\n");
    if(listen(sockfd,10)==-1)
        P(listen);
    printf("listen success\n");
    int connfd=accept(sockfd,(struct sockaddr *)&cli,&cli_len);
    if(connfd==-1)
        P(accept);
    printf("accept success\n");
    printf("[%s] [%d]\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
    return connfd;
} 

int server_send(int connfd, const char *buf, int count)
{
    int ret;
    ret = write(connfd, buf, count);
    if (ret == -1) 
    {
        perror("server->read");
        return -1;
    } else
        return ret;
}

int server_recv(int connfd, char *buf, int count)
{
    int ret;
    ret = read(connfd, buf, count);
    if (ret == -1) 
    {
        perror("server_read");
        return -1;
    } 
    else if (ret == 0) 
    {
        fprintf(stderr, "server_read: end-of-file\n");
        return 0;
    } else
        return ret;
}

void server_exit(int fd)
{
    close(fd);
}
